<?php

class email {
   
   private static $_startTime = NULL;
   private static $_cat       = '';
   private static $_from      = '';
   private static $_from_name = '';
   private static $_sign      = 0;
   private static $_as_html   = 1;
   
   
   
   /**
    * Send email to the Queue
    * 
    * @param string $to recipient email
    * @param string $subject email subject
    * @param string $message email message
    * @param array $params additiona parameters - array('recipient_name' => value, 'attachment' => value)
    * @return boolean 
    */
   public static function queue($to, $subject, $message, $params = array())
   {
      // TODO: attachment processing needs to be implemented
      // $params['attachment'];
      $to_name = !empty($params['recipient_name']) ? $params['recipient_name'] : '';
      
      if(!self::$_from) self::reset();
      
      $DB = database::getInstance();
      $DB->DB_QueryBuilder('INSERT INTO `meccano_outbox` (
            `cdate`, `udate`, `sdate`, `as_html`,
            `cat`, 
            `sign`,
            `done`, 
            `from`, 
            `from_name`,
            `recipient`, 
            `recipient_name`,
            `subject`, 
            `message`
         ) VALUES (
            NOW(), NOW(), "'. self::$_startTime .'", '. self::$_as_html .',
            "%s",
            %i,
            0, 
            "%s", 
            "%s",
            "%s", 
            "%s", 
            "%s",
            "%s"
         )', array(
            self::$_cat,
            self::$_sign,
            self::$_from,
            self::$_from_name,
            $to,
            $to_name,
            $subject,
            $message
         ));

      return (boolean)$DB->DB_Query();
   }
   

   
   /**
    * Flash Email Queue
    *  
    */
   public static function flashQueue()
   {
      $DB = database::getInstance();
      $DB->sql = 'SELECT * FROM `meccano_outbox` WHERE `done` = 0 AND `sdate` < NOW() ORDER BY `sdate` ASC LIMIT 0, 20';
      $DB->DB_Fetch();

      if($DB->fetched)
      {
         // TODO: add manage tool to switch between: sendmail | smtp
         include(ROOT . LIBRARY .'/phpmailer/class.phpmailer.php');
         $ids = array();
         $MAIL = new PHPMailer();
         $MAIL->set('CharSet', 'UTF-8');
         
         foreach($DB->fetched AS $v)
         {
            $MAIL->ClearAddresses();
            $MAIL->ClearAllRecipients();
            $MAIL->IsHTML((boolean)$v['as_html']);
            $MAIL->SetFrom($v['from'], $v['from_name']);
            $MAIL->AddAddress($v['recipient'], $v['recipient_name']);
            $MAIL->set('Subject', $v['subject']);
            $MAIL->MsgHTML($v['message']);
            if($MAIL->Send())
            {
               $ids[] = $v['id'];
            }
         }
         
         if(!empty($ids))
         {
            $DB->sql = 'UPDATE `meccano_outbox` SET `done` = 1 WHERE `id` IN ('. join(',', $ids) .')';
            $DB->DB_Query();
         }
      }
   }
   
   
   /**
    * Get email body from template
    * 
    * @param array $vars
    * @param string $tpl 
    */
   public static function getMessageFromTemplate($vars, $tpl)
   {
      include_once(ROOT . LIBRARY .'/smarty/meccano.smarty.class.inc');
      $SMARTY = new MeccanoSmarty();
      $SMARTY->assign('data', $vars);
      return $SMARTY->fetch($tpl);
   }
   
   
   
   /** 
    * Reset Class to its default values 
    */
   public static function reset()
   {
      self::$_startTime = date('Y-m-d H:s:i');
      self::$_cat       = '';
      self::$_sign      = 0;
      self::$_as_html   = 1;
      self::setSender(config::read('default_send_from', 'system'));
   }
   
   /**
    * Set time on which email has been send
    * 
    * @param string $time - integer or time string
    */
   public static function setStartTime($time)
   {
      if(!is_numeric($time)) $time = strtotime ($time);
      if($time)
      {
         self::$_startTime = date('Y-m-d H:s:i', $time);
      }
   }
   
   
   /**
    * Set email AS HTML
    * 
    * @param boolean $is 
    */
   public static function setAsHtml($is = FALSE)
   {
      if($is) self::$_as_html = 1;
      else    self::$_as_html = 0;
   }
   
   
   /**
    * Set email category
    * 
    * @param string $cat 
    */
   public static function setCategory($cat)
   {
      $allowedCategories = array(
         'dispatch',
         'frontend'
      );
      
      self::$_cat = '';
      if(in_array($cat, $allowedCategories))
      {
         self::$_cat = $cat;
      }
   }
   
   
   /**
    * Set sign for an email
    * 
    * @param integer $int 
    */
   public static function setSign($int)
   {
      self::$_sign = (int)$int;
   }
   
   /**
    * Set email sender
    * 
    * @param string $email
    * @param string $name 
    */
   public static function setSender($email, $name = NULL)
   {
      self::$_from = $email;
      if(!empty($name))
      {
         self::$_from_name = $name;
      }
   }
}